<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="search" placeholder="索引" class="filter-item" style="width: 400px;" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list.slice((currentPage - 1) * pageSize,currentPage * pageSize)"
      border
      fit
      highlight-current-row
      style="width: 80%"
    >

      <el-table-column label="索引" prop="index" align="center" width="300" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.index }}</span>
        </template>
      </el-table-column>

      <el-table-column label="条件" prop="condition" align="center" width="300">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.condition === '0' ? 'info' : 'success'"
            disable-transitions
            size="small"
          >
            {{ scope.row.condition }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="接收者" prop="receiver" align="center" width="200" />

      <el-table-column label="更新时间" prop="timestamp" align="center" width="300">
        <template slot-scope="scope">
          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }} </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @pagination="getList"
      />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="50px" style="width:400px; margin-left:50px;">
        <el-form-item label="索引" prop="index">
          <el-input v-model="temp.index" />
        </el-form-item>
        <el-form-item label="条件" prop="condition">
          <el-input v-model="temp.condition" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create'? createData(): updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'

export default {
  name: 'LogTable',
  // 声明filter方法否则[Vue warn]: Failed to resolve filter: parseTime
  filters: {
    parseTime
  },
  data() {
    return {
      tableKey: 0,
      // dialog
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      temp: {
        index: '',
        timestamp: new Date(),
        condition: '',
        type: ''
      },
      // pagination
      total: 0,
      currentPage: 1,
      pageSize: 2,
      pageSizes: [2, 10, 20],
      // search
      search: '',
      // raw list data
      rawList: null,
      // table list data
      list: null,
      listLoading: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      // Just to simulate the time of the request
      setTimeout(() => {
        this.listLoading = false
      }, 1.5 * 1000)

      //   TODO getIndexConfig
      this.rawList = [{
        timestamp: new Date(),
        receiver: 'Tom',
        index: 'crm-frontend-inner-nginx',
        condition: 'status:500'
      }, {
        timestamp: new Date(),
        receiver: 'Mary',
        index: 'crm-frontend-pad-nginx',
        condition: 'lv:ERROR'
      }, {
        timestamp: new Date(),
        receiver: 'Cindy',
        index: 'crm-frontend-app-nginx',
        condition: 'request_time:5'
      }, {
        timestamp: new Date(),
        receiver: 'Vera',
        index: 'crm-frontend-activity-nginx',
        condition: 'lv:ERROR'
      }]
      this.list = this.rawList
      this.total = this.list.length
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleFilter() {
      if (this.search.length === 0) {
        this.list = this.rawList
      } else {
        this.list = this.rawList.filter(data => !this.search || data.index.toLowerCase().includes(this.search.toLowerCase()))
      }
      this.total = this.list.length
    },
    resetTemp() {
      this.temp = {
        index: '',
        timestamp: new Date(),
        condition: '',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // TODO 后端创建
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: this.temp,
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          //   TODO 后端更新
          this.dialogFormVisible = false
          this.$notify({
            title: 'success',
            message: this.temp,
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    handleDelete(index, row) {
      // TODO 后端删除
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.pagination-container {
  background: #fff;
  padding: 32px 16px;
}
</style>
